<template>
  <div class="form-container">
    <el-form :rules="loginRules" ref="loginForm" :model="loginForm">
      <el-form-item class="formItem" label="账号" prop="username">
        <el-input @keyup.enter.native="handleLogin" v-model="loginForm.username" auto-complete="off" :placeholder="$t('login.username')">
          <i class="el-icon-user-solid" slot="suffix"></i>
        </el-input>
      </el-form-item>
      <el-form-item class="formItem" label="密码" prop="password">
        <el-input @keyup.enter.native="handleLogin" :type="passwordType" v-model="loginForm.password" auto-complete="off" :placeholder="$t('login.password')">
          <i
            class="el-input__icon"
            v-if="this.passwordType === 'password'"
            :class="{ 'el-icon-view': this.passwordType === 'password', 'el-icon-c-scale-to-original': this.passwordType === '' }"
            slot="suffix"
            @click="showPassword"
          />
          <img slot="suffix" class="icon-img" v-else src="@/assets/img/station-ui/no-view.png" @click="showPassword" alt="" />
        </el-input>
      </el-form-item>
      <el-form-item prop="checkBox">
        <el-checkbox v-model="checked" @change="optional">记住账号密码</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click.native.prevent="handleLogin" class="login-submit">{{ $t('login.submit') }} </el-button>
      </el-form-item>
    </el-form>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getRouteDetail, checkRoute } from '@/api/user';
import { getList } from '@/api/product/workorder';

export default {
  name: 'linelogin',
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      tenantMode: this.website.tenantMode,
      loginForm: {
        //租户ID
        // tenantId: "000000",
        tenantId: '',
        //用户名
        username: '',
        //密码
        password: '',
        //账号类型
        type: 'account',
        //工序编码
        routeCode: '',
        //工位编码
        stationCode: '',
        //预加载白色背景
        image: ''
      },
      loginRules: {
        username: [{ required: false, message: '请输入账号', trigger: 'blur' }],
        password: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { min: 1, message: '密码长度最少为6位', trigger: 'blur' }
        ]
        // code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      passwordType: 'password',
      checked: false,
      stationForm: {},
      tableOption: {}
    };
  },
  created() {},
  mounted() {
    let chooseChecked = localStorage.getItem('saber-checked') === 'false' ? false : true;
    this.checked = localStorage.getItem('saber-checked') === 'false' ? false : true;
    let localValue = localStorage.getItem('storedValue');
    let convertedValue = localValue ? JSON.parse(localValue) : '';
    this.loginForm.tenantId = JSON.parse(localStorage.getItem('loginSet')) ? JSON.parse(localStorage.getItem('loginSet')).tenantId : '';
    this.loginForm.username = convertedValue ? convertedValue.username : '';
    this.loginForm.password = convertedValue ? convertedValue.password : '';
    if (chooseChecked && this.loginForm.username && this.loginForm.username) {
      this.checked = true;
    } else {
      this.checked = false;
    }
  },
  watch: {},
  computed: {
    ...mapGetters(['tagWel', 'userInfo'])
  },
  props: [],
  methods: {
    optional(val) {
      if (this.checked) {
        localStorage.setItem('saber-checked', true);
        localStorage.setItem('storedValue', JSON.stringify(this.loginForm));
      } else {
        localStorage.setItem('saber-checked', false);
        localStorage.setItem('storedValue', '');
      }
    },
    showPassword() {
      this.passwordType === '' ? (this.passwordType = 'password') : (this.passwordType = '');
    },
    submitLogin(form, done) {
      this.handleLogin();
      done();
    },
    handleLogin() {
      this.loginForm.tenantId = JSON.parse(localStorage.getItem('loginSet')) ? JSON.parse(localStorage.getItem('loginSet')).tenantId : '';
      this.loginForm.routeCode = JSON.parse(localStorage.getItem('loginSet')) ? JSON.parse(localStorage.getItem('loginSet')).routeCode : '';
      this.loginForm.stationCode = JSON.parse(localStorage.getItem('loginSet')) ? JSON.parse(localStorage.getItem('loginSet')).stationCode : '';
      if (!this.loginForm.tenantId) {
        this.$message({
          type: 'warning',
          message: '请在登录设置中输入租户ID'
        });
        return;
      }
      if (!this.loginForm.routeCode) {
        this.$message({
          type: 'warning',
          message: '请在登录设置中选择工序'
        });
        return;
      }
      if (!this.loginForm.stationCode) {
        this.$message({
          type: 'warning',
          message: '请在登录设置中输入工位编码'
        });
        return;
      }
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '登录中,请稍后。。。',
            spinner: 'el-icon-loading'
          });
          this.$store
            .dispatch('LoginByUsername', this.loginForm)
            .then(() => {
              localStorage.setItem('isLineLogin', true);
              this.getWorkOrderList();
              loading.close();
            })
            .catch(() => {
              loading.close();
            });
        }
      });
    },
    /**
     * 查询工单数据
     */
    getWorkOrderList() {
      let loginSetStationInfo = JSON.parse(localStorage.getItem('loginSetStationInfo') ? localStorage.getItem('loginSetStationInfo') : '{}');
      getList(1, 10, { productionLineId: loginSetStationInfo.lineId, workOrderStatus: '2,3' }).then((res) => {
        let data = this._get(res, 'data.data.records', []);
        if (data.length === 1) {
          this.stationForm = data[0];
          this.checkRouteCode();
        } else {
          this.openWorkOrderNoModal();
        }
      });
    },
    /**
     * 打开选择工单号模态框
     */
    openWorkOrderNoModal() {
      let loginSetStationInfo = JSON.parse(localStorage.getItem('loginSetStationInfo') ? localStorage.getItem('loginSetStationInfo') : '{}');
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: `/api/mes-product/work-order/page?productionLineId=${loginSetStationInfo.lineId}&workOrderStatus=2,3`,
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=mfg_work_order'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      this.stationForm = rowData;
      this.checkRouteCode();
    },
    checkRouteCode() {
      checkRoute(this.stationForm.id, this.loginForm.routeCode).then(() => {
        this.getRouteDetail();
      });
    },
    getRouteDetail() {
      getRouteDetail(this.stationForm.id, this.loginForm.routeCode).then((res) => {
        const data = res.data.data;
        this.stationForm.routeId = data.id;
        this.stationForm.workStationCode = data.code;
        this.stationForm.workStationName = data.name;
        this.stationForm.isFirst = data.isFirst;
        this.stationForm.isLast = data.isLast;
        this.stationForm.stationCode = this.loginForm.stationCode;
        this.bindingStationIsTrue = false;
        this.stationForm.isShowEsop = data.isShowEsop;
        this.stationForm.esopUrl = data.esopUrl;
        this.getStationInfo();
      });
    },
    /**
     * 获取工位信息
     */
    getStationInfo() {
      let params = {
        workOrderNo: this.stationForm.orderNo,
        stationCode: this.stationForm.stationCode,
        routeCode: this.stationForm.workStationCode
      };
      this.getBindingStationInfo(params);
    },
    /**
     * 获取工序绑定工位信息
     */
    async getBindingStationInfo(params) {
      let bindingStationInfo = await this.$store.dispatch('bindingStation', params);
      let workStationInfo = {
        workStationCode: this.stationForm.workStationCode, //配置工站编码
        workorderStationId: this._get(bindingStationInfo, 'data.data.id', ''), //工序和工位绑定ID
        stationId: this._get(bindingStationInfo, 'data.data.stationId', ''), //工位ID
        stationName: this._get(bindingStationInfo, 'data.data.stationName', ''), //工位名称
        routeStationId: this._get(bindingStationInfo, 'data.data.routeId', ''), //工序ID
        routeName: this._get(bindingStationInfo, 'data.data.routeName', ''), //工序名称
        lineId: this._get(bindingStationInfo, 'data.data.lineId', ''), //产线ID
        lineName: this._get(bindingStationInfo, 'data.data.lineName', ''), //产线名称
        workOrderId: this._get(bindingStationInfo, 'data.data.workOrderId', ''), //工单号ID
        workOrderNo: this._get(bindingStationInfo, 'data.data.workOrderNo', ''), //工单号
        workshopName: this._get(bindingStationInfo, 'data.data.workshopName', ''), //车间名称
        planQuantity: this._get(this.stationForm, 'planQuantity', 0), //计划数量
        passQuantity: this._get(bindingStationInfo, 'data.data.passQuantity', 0), //过站数量
        waitingQuantity: this._get(bindingStationInfo, 'data.data.waitingQuantity', 0), //等待过站数量
        isShowEsop: this._get(this.stationForm, 'isShowEsop', ''), //是否启用esop
        esopUrl: this._get(this.stationForm, 'esopUrl', '') //esop地址
      };
      this.$store.commit('stationOperation/setworkStationInfo', workStationInfo);
      this.$router.replace('/product/model-manage/station-op-template');
    }
  }
};
</script>

<style scoped lang="scss">
.icon-img {
  width: 40px;
  height: 40px;
  overflow: hidden;
}

.form-container {
  margin-top: 20px;
  background: #ffffff;
  .formItem {
    display: flex;
    border-bottom: 1px solid #dcdfe6;
  }
  ::v-deep .el-form-item__label {
    height: 47px;
    line-height: 47px;
    font-size: 20px;
    width: 60px;
    text-align: left;
    font-weight: bold;
  }
  ::v-deep .el-form-item__content {
    width: 100%;
    .el-input__suffix {
      font-size: 20px;
      top: 6px;
    }
  }
}

.login-submit {
  width: 100%;
  height: 47px;
  border: 1px solid #409eff;
  background: linear-gradient(90deg, #2192f1 0%, #37abf8 100%);
  box-shadow: 0px 5px 15px 0px rgba(52, 105, 246, 0.2);
  border-radius: 6px;
  font-size: 22px;
  font-weight: 400;
  color: #ffffff;
  line-height: 26px;
}
</style>
